package cn.exrick.xboot.modules.callApi;

import cn.exrick.xboot.common.jiuqiCommon.callAPIUtil.CallApiUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.commonLink.entity.CommonLink;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.trace.http.HttpTrace;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@Api(description = "后台调用对应子系统接口")
@RequestMapping("/xboot/api")
@Transactional
public class CallApi {

    @Autowired
    private SecurityUtil securityUtil;

    /**
     * njp add 20190813 调用对接子系统的通用接口（解决前端无法请求问题）begin
     *
     * @param messageAll
     * @return
     */
    @RequestMapping(value = "/callApi", method = RequestMethod.POST)
    @ApiOperation(value = "调用子系统接口")
    public JSONObject callApi(@RequestBody JSONObject messageAll) {
        log.info("调用callApi");
        log.info("接受参数messageAll:" + messageAll.toString());

        JSONObject json = null;
        String url = null;
        JSONObject message = null;
        //避免常见的空指针异常
        if (!messageAll.isEmpty()) {
            message = messageAll.getJSONObject("message");
            log.info("请求报文:" + message.toString());
            //String url =message.getString("url");
            url = messageAll.getString("url");
            log.info("目标地址url:" + url);
        }
        //return new ResultUtil<BacklogOrFull>().setData(backlogOrFull);
        CallApiUtil call = new CallApiUtil();
        try {
            if (url != null && !url.equals("") && url.length() != 0 && !url.trim().isEmpty()) {
                json = call.doPostGetJson(message, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("callApi的返回报文："+json);
       // return new ResultUtil<JSONObject>().setData(json);
        return json;
    }



    @RequestMapping(value = "/callApi123", method = RequestMethod.POST)
    @ApiOperation(value = "调用子系统接口")
    public String callApi123(@RequestBody JSONObject messageAll) {

        return "1321321231";
    }

    /**
     * njp add 20190813 调用对接子系统的通用接口（解决前端无法请求问题）end
     */

    @RequestMapping(value = "/callApitest", method = RequestMethod.POST)
    @ApiOperation(value = "通过id获取")
    public Result<JSONObject> callApitest(@RequestBody JSONObject message, @Param("url") String url) {
        log.info("调用callApitest");
        log.info("message:" + message.toString());
        log.info("url:" + url);
        JSONObject json = null;
        //return new ResultUtil<BacklogOrFull>().setData(backlogOrFull);
        CallApiUtil call = new CallApiUtil();
        try {
            if (url != null && !url.equals("") && url.length() != 0 && !url.trim().isEmpty()) {
                json = call.doPostGetJson(message, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultUtil<JSONObject>().setData(json);
    }


    /**
     * njp add 20190813 调用对接子系统的通用接口（解决前端无法请求问题）begin
     *
     * @return
     */
    @RequestMapping(value = "/callApiForm", method = RequestMethod.POST)
    @ApiOperation(value = "调用子系统接口")
    public void callApiForm(@Param("name") String name, HttpServletResponse response, HttpServletRequest resquest) {
        log.info("接受name:"+name);
      /*  log.info("接受参数messageAll:" + messageAll.toString());
        JSONObject json = null;
        String url = null;
        JSONObject message = null;
        //避免常见的空指针异常
        if (!messageAll.isEmpty()) {
            message = messageAll.getJSONObject("message");
            log.info("表单请求报文:" + message.toString());
            url = messageAll.getString("url");
            log.info("目标地址url:" + url);
        }
        String redirctUrl = null;
        try {
            if (url != null && !url.equals("") && url.length() != 0 && !url.trim().isEmpty()) {
                redirctUrl = CallApiUtil.callRedirect(message, url, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("重定向地址"+redirctUrl);*/
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@");
        try {
           // response.sendRedirect("http://10.39.5.48:9797/portal/sso?userCode=3974FBE7EEA5A80BE22F8D01268A2BD5FA2E5C4E1B5DF3B9&templateName=WJZGL1");
             //response.sendRedirect("http://10.1.13.28:8989/portal/GetWorkFlowServlet");

            //1、创建httpClient
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://10.1.13.28:8989/newTest/openNew?userCard=123231");
            CloseableHttpResponse xxx = client.execute(httpGet);


           /* JSONObject  backInfo=null;
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost("http://10.1.13.28:8989/portal/GetWorkFlowServlet");
            //post表单
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();


            //UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
            //post.setEntity(urlEncodedFormEntity);
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            //HttpEntity entity = res.getEntity();
            System.out.println(response1);*/



        } catch (IOException e) {
            e.printStackTrace();
        }

        //log.info("json.toString()"+json);
    }


   /* @RequestMapping(value = "/callApiFormtest", method = RequestMethod.POST)
    @ApiOperation(value = "调用子系统接口")
    public void callApiFormtest(@RequestBody JSONObject messageAll, HttpServletResponse response) {
        log.info("接受参数messageAll:" + messageAll.toString());
        JSONObject json = null;
        String url = null;
        JSONObject message = null;
        //避免常见的空指针异常
        if (!messageAll.isEmpty()) {
            message = messageAll.getJSONObject("message");
            log.info("表单请求报文:" + message.toString());
            url = messageAll.getString("url");
            log.info("目标地址url:" + url);
        }
        String redirctUrl = null;
        try {
            if (url != null && !url.equals("") && url.length() != 0 && !url.trim().isEmpty()) {
                redirctUrl = CallApiUtil.callRedirect(message, url, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("重定向地址");
        *//*return s;*//*
    }*/

    @RequestMapping("alipayforward")
    public String alipayforward(@Param("userCode")String  userCode, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //String contNo =req.getParameter("contNo"); //保单号
       // User u = securityUtil.getCurrUser();
        // 清除持久上下文环境 避免后面语句导致持久化
       // String username = u.getUsername();
       // log.info("当前登录用户："+username);

        //String username=   principal.getName();
        log.info("当前登录用户："+userCode);
        log.info("访问/downloadRequestElecCont.action");
        return "redirect:http://10.39.5.48:9797/portal/sso?userCode=3974FBE7EEA5A80BE22F8D01268A2BD5FA2E5C4E1B5DF3B9&templateName=WJZGL1";
    }

}
